package com.itx.gatewayx.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itx.gatewayx.domain.ChatMessage;
import com.itx.gatewayx.domain.ChatSession;
import com.itx.gatewayx.domain.User;
import com.itx.gatewayx.mapper.ChatMessageMapper;
import com.itx.gatewayx.mapper.ChatSessionMapper;
import com.itx.gatewayx.service.ChatService;
import com.itx.gatewayx.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 聊天服务实现类
 *
 * @author itx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
    
    private final ChatSessionMapper sessionMapper;
    private final ChatMessageMapper messageMapper;
    private final UserService userService;
    
    @Override
    public List<ChatSession> getUserSessions(Long userId) {
        List<ChatSession> sessions = sessionMapper.selectSessionsByUserId(userId);
        
        // 获取每个会话的未读消息数
        sessions.forEach(session -> {
            int unreadCount = getUnreadCount(session.getId(), userId);
            session.setUnreadCount(unreadCount);
        });
        
        return sessions;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatSession getOrCreateSession(Long userId, Long targetUserId) {
        // 先查询是否已存在会话
        ChatSession session = sessionMapper.selectByUserIdAndTargetUserId(userId, targetUserId);
        
        if (session == null) {
            // 创建新会话
            session = new ChatSession();
            session.setUserId(userId);
            session.setTargetUserId(targetUserId);
            session.setCreateTime(new Date());
            session.setUpdateTime(new Date());
            
            sessionMapper.insert(session);
            
            // 同时创建对方视角的会话
            ChatSession targetSession = new ChatSession();
            targetSession.setUserId(targetUserId);
            targetSession.setTargetUserId(userId);
            targetSession.setCreateTime(new Date());
            targetSession.setUpdateTime(new Date());
            
            sessionMapper.insert(targetSession);
        }
        
        // 获取会话目标用户信息
        User targetUser = userService.getById(targetUserId);
        if (targetUser != null) {
            session.setTargetUser(targetUser);
        }
        
        // 获取未读消息数
        int unreadCount = getUnreadCount(session.getId(), userId);
        session.setUnreadCount(unreadCount);
        
        return session;
    }
    
    @Override
    public IPage<ChatMessage> getChatMessages(Long current, Long size, Long chatId) {
        Page<ChatMessage> page = new Page<>(current, size);
        return messageMapper.selectMessagePage(page, chatId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendMessage(ChatMessage message) {
        // 设置消息状态
        message.setStatus(0); // 未读
        message.setCreateTime(new Date());
        message.setDelFlag(0);
        
        // 保存消息
        messageMapper.insert(message);
        
        // 更新会话最后一条消息
        sessionMapper.updateLastMessage(message.getChatId(), message.getId());
        
        // 更新对方视角的会话 (需要先查询会话)
        ChatSession session = sessionMapper.selectById(message.getChatId());
        if (session != null) {
            // 查询对方视角的会话
            ChatSession targetSession = sessionMapper.selectByUserIdAndTargetUserId(
                    session.getTargetUserId(), session.getUserId());
            
            if (targetSession != null) {
                sessionMapper.updateLastMessage(targetSession.getId(), message.getId());
            }
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markMessagesAsRead(Long chatId, Long userId) {
        return messageMapper.markMessagesAsRead(chatId, userId) > 0;
    }
    
    @Override
    public int getUnreadCount(Long chatId, Long userId) {
        return messageMapper.countUnreadMessages(chatId, userId);
    }
    
    @Override
    public int getTotalUnreadCount(Long userId) {
        int totalCount = 0;
        
        // 获取用户所有会话
        List<ChatSession> sessions = getUserSessions(userId);
        
        // 计算所有会话的未读消息总数
        for (ChatSession session : sessions) {
            totalCount += getUnreadCount(session.getId(), userId);
        }
        
        return totalCount;
    }
} 